﻿using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Application = UnityEngine.Device.Application;

namespace Editor.Tools.UI
{
    public static class UITool
    {
        private const string UIPrefabRootPath = "Resources/Prefabs/UI/Prefab";
        private const string UIPathBin = "GameConfig/UIPath.bin";
        [MenuItem("Tools/UI/UI预制路径导出")]
        public static void ExportUIPrefabPath()
        {
            if (File.Exists(UIPathBin))
            {
                File.Delete(UIPathBin);
            }
            
            var paths = GetAllPrefabRelativePaths(Path.Combine(Application.dataPath, UIPrefabRootPath));
            using (var fs = new FileStream(Path.Combine(Application.dataPath, UIPathBin), FileMode.Create))
            {
                using (var bw = new BinaryWriter(fs))
                {
                    foreach (var path in paths)
                    {
                        string fileName = Path.GetFileNameWithoutExtension(path);
                        bw.Write(fileName);
                        bw.Write(path.Replace(".prefab", ""));
                        // Debug.Log($"fileName: {fileName}, path: {path}");
                    }
                }
            }
        }
        
        [MenuItem("Tools/UI/打印UI预制路径")]
        public static void PrintUIPrefabPath()
        {
            if (!File.Exists(Path.Combine(Application.dataPath, UIPathBin)))
            {
                Debug.LogError("UIPath.bin不存在");
                return;
            }
            
            using (var fs = new FileStream(Path.Combine(Application.dataPath, UIPathBin), FileMode.Open))
            {
                using (var br = new BinaryReader(fs))
                {
                    while (br.BaseStream.Position != br.BaseStream.Length)
                    {
                        string fileName = br.ReadString();
                        string path = br.ReadString();
                        Debug.Log($"fileName: {fileName}, path: {path}");
                    }
                }
            }
        }
        
        private static string[] GetAllPrefabRelativePaths(string folderPath)
        {
            string[] allFiles = Directory.GetFiles(folderPath, "*.prefab", SearchOption.AllDirectories);
            return allFiles.Select(file => Path.GetRelativePath(folderPath, file)).ToArray();
        }
    }
}